package com.seecen.utils;

import cn.hutool.core.util.ObjectUtil;
import io.jsonwebtoken.*;
import lombok.Data;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "jwt.token")
public class JwtHelper {

    //token的失效时间 分钟
    private long tokenExpiration;
    //私钥
    private String tokenSingKey;

    //生成token
    public String createToken(Long userId) {
        String token = Jwts.builder()
                .setSubject("HHYY-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration * 1000 * 60))
                .claim("userId", userId)
                .signWith(SignatureAlgorithm.HS512, tokenSingKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
//        log.info("token = {}", token);
        return token;
    }

    //解析token
    public Long getUserId(String token) {
        if(ObjectUtil.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey(tokenSingKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        log.info("userId = {}", userId);
        return userId.longValue();
    }

    //判断token是否有效
    public boolean isExpiration(String token) {
        try {
            boolean isExpire = Jwts.parser().setSigningKey(tokenSingKey)
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration().before(new Date());
            return isExpire;
        } catch (Exception e) {
            //异常 也可以当做失效 重新生成
            return true;
        }
    }
}
